#include "Scene.h"
#include "SceneEntity.h"
#include "Utility/Utility.h"

CScene::CScene( SceneID sceneID, const std::string& strSceneName )
	: m_SceneID(sceneID)
	, m_strName(strSceneName)
	, m_EntityIDSeed(0)
{

}

CScene::~CScene()
{
	Destroy();
}

bool CScene::Init()
{
	return true;
}


bool CScene::Load( const std::string& filepath )
{
	return true;
}

void CScene::Destroy()
{
	std::map<EntityID, CSceneEntity*>::iterator mit = m_EntityMap.begin();
	for (; mit != m_EntityMap.end(); ++mit)
	{
		CSceneEntity* pEntity = mit->second;
		m_DeferedDeleteEntities.push_back(pEntity);
	}
	m_EntityMap.clear();

	_ClearDeferedEntities();
}

void CScene::Update( float fTime )
{
	std::map<EntityID, CSceneEntity*>::iterator mit = m_EntityMap.begin();
	for (; mit != m_EntityMap.end(); ++mit)
	{
		CSceneEntity* pEntity = mit->second;
		pEntity->Update(fTime);
	}
}

void CScene::Render()
{
	std::map<EntityID, CSceneEntity*>::iterator mit = m_EntityMap.begin();
	for (; mit != m_EntityMap.end(); ++mit)
	{
		CSceneEntity* pEntity = mit->second;
		pEntity->Render();
	}
}

CSceneEntity* CScene::GetEntityByID( SceneID entityID )
{
	std::map<EntityID, CSceneEntity*>::iterator find_it = m_EntityMap.find(entityID);
	if (find_it != m_EntityMap.end())
	{
		return find_it->second;
	}
	return NULL;
}

void CScene::DestroyEntity( SceneID entityID )
{
	std::map<EntityID, CSceneEntity*>::iterator find_it = m_EntityMap.find(entityID);
	if (find_it != m_EntityMap.end())
	{
		CSceneEntity* pEntity = find_it->second;
		m_DeferedDeleteEntities.push_back(pEntity);
		m_EntityMap.erase(find_it);
	}
}

void CScene::DestroyEntity( CSceneEntity* pSceneEntity )
{
	DBG_ASSERT(pSceneEntity != NULL);

	EntityID id = pSceneEntity->GetID();
	DestroyEntity(id);
}

EntityID CScene::_GenerateEntityID()
{
	EntityID newID = m_EntityIDSeed;
	m_EntityIDSeed++;
	return newID;
}

void CScene::_ClearDeferedEntities()
{
	std::vector<CSceneEntity*>::iterator vit = m_DeferedDeleteEntities.begin();
	for(; vit != m_DeferedDeleteEntities.end(); ++vit)
	{
		CSceneEntity* pEntity = *vit;
		SAFE_DELETE(pEntity);
	}
	m_DeferedDeleteEntities.swap(std::vector<CSceneEntity*>());
}
